package hanelsoft.vn.dictionaylearn.control.service;

import hanelsoft.vn.dictionaylearn.R;
import hanelsoft.vn.dictionaylearn.control.activity.ContentView;
import hanelsoft.vn.dictionaylearn.model.common.Utility;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFile;
import hanelsoft.vn.dictionaylearn.model.db.DatabaseFileList;
import hanelsoft.vn.dictionaylearn.model.db.VocabularySQLiteHelper;
import hanelsoft.vn.dictionaylearn.model.entity.InfoVocabularyContent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import android.app.ProgressDialog;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

public class TooltipRunServiceLayoutParams extends Service{
	String tag ="[RunServiceLayoutParams]";
	String MIMETYPE = "text/html";
	String ENCODING = "UTF-8";
	WindowManager.LayoutParams params;
	WindowManager mWindowManager;
	View mView;
	SharedPreferences mSharedPreferences, share, sharePlaySound, prefs, positionVocabulary;
	ArrayList<InfoVocabularyContent> arrayVocabulary;
	InfoVocabularyContent infoVocabulary;
	VocabularySQLiteHelper mVocabularySQLiteHelper = new VocabularySQLiteHelper(this);
	private TextView contentview_Sound;
    private WebView contentview_Content = null;
    int mCurrentWordId;
    private String mCurrentWord;
    private String mSelectedDB;
    private String mContentStyle;
    private String mSourcesound;
	private String mDBExtension;
	private String mDBPath;
	private DatabaseFileList mDBList;
	private DatabaseFile mDBFile;
	boolean found = false;
	File f;
	String fullPathFilePro;
	MediaPlayer mp;
	private ProgressDialog pd = null;
	String content;
	@Override
	public void onCreate() {
		Log.i(tag, "run create");
		super.onCreate();
		setOverLayout();
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(tag, "run onStartCommand");
		int check = mSharedPreferences.getInt("isRun", 0);
		if(check == 1)
		{
			mSharedPreferences.edit().putInt("isRun", 0).commit();
			Intent i = new Intent(TooltipRunServiceLayoutParams.this, TooltipRunServiceLayoutParams.class);
			stopService(i);
		}
		else
		{
			mSharedPreferences.edit().putInt("isRun", 1).commit();
		}
		
		return super.onStartCommand(intent, flags, startId);
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
//		share.edit().putInt("isRunService", 0).commit();
		mWindowManager.removeView(mView);
		Log.i(tag, "run onDestroy");
	}
	@Override
	public IBinder onBind(Intent intent) {
		Log.i(tag, "run onBind");
		return null;
	}
	public void setOverLayout()
	{
		mSharedPreferences = this.getSharedPreferences("check", 1);
		sharePlaySound = getSharedPreferences("CBplaysound", 1);
		share = getSharedPreferences("Time", 1);
		String nameList = share.getString("namelist", null);
		arrayVocabulary = new ArrayList<InfoVocabularyContent>();
		arrayVocabulary = mVocabularySQLiteHelper.viewAllVocabularyContent(nameList);
		share = getSharedPreferences("Time", 1);
		int positionVocabulary = share.getInt("positionVocabulary", 0);
		Log.i(tag, "get position vocabulary: "+positionVocabulary);
		if((positionVocabulary + 1) < arrayVocabulary.size())
		{
			share.edit().putInt("positionVocabulary", (positionVocabulary + 1)).commit();
			Log.i(tag, "set position vocabulary: "+(positionVocabulary + 1));
		}
		else
		{
			share.edit().putInt("positionVocabulary", 0).commit();
			Log.i(tag, "set position vocabulary: "+0);
		}
		positionVocabulary = share.getInt("positionVocabulary", 0);
		Log.i(tag, "get position vocabulary2: "+positionVocabulary);
		infoVocabulary = arrayVocabulary.get(positionVocabulary);
		//
		mDBExtension = getResources().getString(R.string.dbExtension);
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        	mDBPath = getResources().getString(R.string.dbPath);
        }
        else
        {
        	mDBPath = getResources().getString(R.string.dbPathNotSDCard);
        }
        //mDBPath = getResources().getString(R.string.dbPath);
        mDBList = new DatabaseFileList(mDBPath,mDBExtension);
        //
        mDBFile = mDBList.items.get(0);
        mCurrentWord = infoVocabulary.getWord();
	    mSelectedDB = mDBFile.fileName;
	    mContentStyle = mDBFile.style;
	    mSourcesound = mDBFile.sourceLanguage;
	    sharePlaySound = getSharedPreferences("CBplaysound", 1);
        //
		mSharedPreferences.edit().putInt("isRun", 0).commit();
		mWindowManager = (WindowManager)getApplicationContext().getSystemService(WINDOW_SERVICE);
		LayoutInflater mLayoutInflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
		mView = mLayoutInflater.inflate(R.layout.layoutparams_overlay, null);
		TextView text = (TextView)mView.findViewById(R.id.layoutparams_overlay_phonetic);
		contentview_Content = (WebView)mView.findViewById(R.id.layoutparams_overlay_Content);
		text.setText(mCurrentWord);
		text.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(v.getContext(), ContentView.class);
				i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    			i.putExtra("word", mCurrentWord);
    	        prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    	        String savedDB = prefs.getString("defaultDictionary", ""); //Default dictionary is the first dictionary in the list
    			String savedDBPath = prefs.getString("defaultDictionaryPath", ""); //Default dictionary is the first dictionary in the list
    			if (savedDB.trim().equals("") || savedDBPath.trim().equals(""))
    			{
    				if (mDBList != null && mDBList.items.size() > 0)
    				{
    					mDBFile = mDBList.items.get(0);
    				}
    				else
    				{
    					mDBFile = null;
    				}
    			}
    			else
    			{
    				if (mDBList != null && mDBList.items.size() > 0)
    				{
    					for (DatabaseFile d : mDBList.items)
    					{
    						if (d.fileName.equals(savedDB) && d.path.equals(savedDBPath))
    						{
    							mDBFile = d;
    							found = true;
    							break;
    						}
    					}
    					if (!found)
    					{
    						mDBFile = mDBList.items.get(0);
    					}
    				}
    				else
    				{
    					mDBFile = null;
    				}
    			}
    			i.putExtra("db", mDBFile.fileName);
    			i.putExtra("dbName",mDBFile.dictionaryName);
    			i.putExtra("style", mDBFile.style);
    			i.putExtra("sourcesound", mDBFile.sourceLanguage);
                startActivity(i);
			}
		});
		ImageButton btnStop = (ImageButton)mView.findViewById(R.id.layoutparams_overlay_exit);
		btnStop.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				share.edit().putInt("positionVocabulary", 0).commit();
				Intent mIntent = new Intent(TooltipRunServiceLayoutParams.this, TooltipAlarmServiceLayoutParams.class);
				stopService(mIntent);
				Intent i = new Intent(TooltipRunServiceLayoutParams.this, TooltipRunServiceLayoutParams.class);
				stopService(i);
			}
		});
		initWebview();
		content = getContentByWord(mCurrentWord);
    	showContent(content);
		params = new WindowManager.LayoutParams(
		            WindowManager.LayoutParams.WRAP_CONTENT,
		            WindowManager.LayoutParams.WRAP_CONTENT,
		            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
		            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
		            PixelFormat.TRANSLUCENT);
		//Get size of screen
		WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		@SuppressWarnings("deprecation")
		int width = display.getWidth();  // deprecated
		@SuppressWarnings("deprecation")
		int height = display.getHeight();  // deprecated
//		params.width = 150;
//		params.height = 100;
		if(width % 4 != 0)
		{
			width = width - (width % 4);
		}
		if(height % 4 != 0)
		{
			height = height - (height % 4);
		}
		params.width = (width/4)*3;
		params.height = height/4;
		params.gravity = Gravity.BOTTOM|Gravity.RIGHT;
		mWindowManager.addView(mView , params);
	}
	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		Log.i(tag, "run onStart");
		super.onStart(intent, startId);
	}
	@Override
	public boolean onUnbind(Intent intent) {
		Log.i(tag, "run onUnbind");
		return super.onUnbind(intent);
	}
	public void initWebview()
    {
    	contentview_Content.setBackgroundColor(Color.argb(255, 255, 255, 255));
    	contentview_Content.setWebViewClient(new WebViewClient() 
        {
        	public void onPageFinished(WebView view, String url)
        	{
        		if (pd != null)
        		{
        			pd.dismiss();
        			pd = null;
        		}
        	}
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		try
        		{
            		String arrUrlPart[] = url.split("://");
            		
            		if (arrUrlPart[0].equals("entry"))
            		{
            			String content = getContentByWord(arrUrlPart[1]);
            			showContent(content);
            		}
            		else if (arrUrlPart[0].equals("http"))
            		{
            	         try {
            	        	 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));             	        	 
            	         } catch (Exception ex) {
                             ex.printStackTrace();
            	         }             			
            		}
        		}
        		catch (Exception ex)
        		{
        			ex.printStackTrace();
        		}
        		return true;
        	}
        });
    }
    public String getContentByWord(String word)
    {
    	Uri uri = Uri.parse("content://hanelsoft.vn.dictionaylearn.model.common.VocadictProvider/dict/" + mSelectedDB + "/contentWord/" + word);
    	ContentResolver resolver = getContentResolver();
    	Cursor result = resolver.query(uri, null, null, null, null);
        if (result != null && result.getCount() > 0)
        {
        	result.moveToFirst();
        	content = Utility.decodeContent(result.getString(result.getColumnIndex("content")));
        	mCurrentWordId = result.getInt(result.getColumnIndex("id"));
        	mCurrentWord = result.getString(result.getColumnIndex("word"));
        	showSound(mCurrentWord);
        }
        else
        {
        	content = getString(R.string.errorWordNotFound)+" '"+word+"'";
        	mCurrentWordId = -1;
        	mCurrentWord = "";
        	showSound(mCurrentWord);
        }
        content = formatContent(content);
        result.close();
        return content;
    }
	public String formatContent(String content)
    {
		StringBuilder htmlData = new StringBuilder();
		htmlData.append("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
		if (mContentStyle != null && !mContentStyle.equals(""))
		{
			htmlData.append("<head><style type=\"text/css\">"+mContentStyle+"</style></head>\n");
		}
		htmlData.append("<body><font face=\"Times New Roman\" size=\"3\">");

		htmlData.append(content);
		
		htmlData.append("</font></body></html>");
		
		return htmlData.toString();
    }
    
    public void showContent(String content)
    {
    	if (content != null)
    	{
    		contentview_Content.loadDataWithBaseURL (null, content, MIMETYPE, ENCODING,"about:blank");
    	}
    }
    public void showSound(String mCurrentWord)
    {
    	contentview_Sound = (TextView)mView.findViewById(R.id.layoutparams_overlay_Sound);
    	contentview_Sound.setEnabled(false);
    	contentview_Sound.setBackgroundResource(R.drawable.bg_params);
    	final String fullPathFilePro;
    	if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    		fullPathFilePro = getString(R.string.soundPath) + mSourcesound + "/" + mCurrentWord + ".wav";
        }
        else
        {
        	fullPathFilePro = getString(R.string.soundPathNotSDCard) + mSourcesound + "/" + mCurrentWord + ".wav";
        }
       	//final String fullPathFilePro = getString(R.string.soundPath) + mSourcesound + "/" + mCurrentWord + ".wav";
		f = new File(fullPathFilePro);
		if (f.exists())
		{
			contentview_Sound.setEnabled(true);
			contentview_Sound.setBackgroundResource(R.drawable.icon_sound);
			contentview_Sound.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(mp.isPlaying() == false)
					{
						mp.start();
					}
					else
					{
						mp.stop();
						mp.start();
					}
				}
			});
			mp = new MediaPlayer();
			try {
				mp.setDataSource(fullPathFilePro);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				mp.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			mp.setLooping(false);
			mp.setVolume(1.0f, 1.0f);
			if(sharePlaySound.getInt("playsound", 0) == 1)
			{
				if(mp.isPlaying() == false)
				{
					mp.start();
				}
				else
				{
					mp.stop();
					mp.start();
				}
			}
		}
		else
		{
		}
    }
}
